package com.shujia.liaotian;

import com.shujia.liaotian.bean.Message;
import com.shujia.liaotian.bean.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Client {
    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("localhost", 8000);

        //登录
        login(socket);

        //启动获取用户列表线程
        new GetLoinList(socket).start();


    }

    public static void login(Socket socket) {

        try {
            OutputStream outputStream = socket.getOutputStream();
            //通过对象流发送对象
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

            User user = new User();
            user.setName("数加");
            user.setData(new Date());
            user.setPassword("123456");

            objectOutputStream.writeObject(user);
            objectOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

class GetLoinList extends Thread {
    private Socket socket;

    public GetLoinList(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {


        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

            ArrayList users;
            while ((users = (ArrayList) objectInputStream.readObject()) != null) {
                System.out.println("id\t用户名\tip\t上线时间");
                for (Object o : users) {
                    User user = (User) o;
                    System.out.println(user.getId() + '\t' + user.getName() + "\t" + user.getIp() + "\t" + user.getData());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
